#include <iostream>
#include <curl/curl.h>
#include <curl/easy.h>
#include <json/json.h>
#include <boost/thread/mutex.hpp>

#include "ServerManager.h"
#include "ClientServer.h"
#include "trace_worker.h"
#include "ClientManager.h"
#include "Base64.h"
#include "JsonHelper.h"


static boost::mutex g_insMutexCalc;

CClientServer* CClientServer::_instance = NULL;

CClientServer* CClientServer::instance() 
{	
	if (NULL == _instance)
	{
		boost::unique_lock<boost::mutex> guardMutex(g_insMutexCalc);
		if (NULL == _instance)
		{
			_instance = new CClientServer;
		}
	}
	return _instance;
}

CClientServer::CClientServer()
:m_websocket(m_subscriber)
{

}

CClientServer::~CClientServer()
{}

void CClientServer::RecieveMessage(const char *channel_name, const char *message, int len)
{
    if (message == NULL || len <= 0)
    {
        return ;
    }
    CClientServer::instance()->SendWSData(channel_name, message);
}

void CClientServer::run()
{
    std::ifstream ifs("config.json");
    rapidjson::IStreamWrapper isw(ifs);
    rapidjson::Document configDocument;
    if (configDocument.ParseStream(isw).HasParseError())
    {
        printf("GetParseError %d  %s\n", configDocument.GetParseError(), __FUNCTION__);
        return;
    }

    int wsPort = configDocument["WEB_SOCKET"]["port"].GetInt();
    std::string redisHost = configDocument["REDIS"]["host"].GetString();
	int redisPort = configDocument["REDIS"]["port"].GetInt();

    m_notifyMessageFn = &CClientServer::RecieveMessage;
    bool ret = m_subscriber.init(m_notifyMessageFn);
    if (!ret)
    {
        printf("Init failed.\n");
        return;
    }

    ret = m_subscriber.connect(redisHost, redisPort);
    if (!ret)
    {
        printf("Connect failed.\n");
        return;
    }
    
    m_websocket.run(wsPort);
}

void CClientServer::SendWSData(const std::string &openId, const std::string &message)
{   trace_worker();
    m_websocket.send(openId, message);
}



